package codeRandomThoughts.Test116填充每个节点的下一个右侧节点指针;


import java.util.LinkedList;
import java.util.Queue;

public class Solution {
    public Node connect(Node root) {
        Node node = root;
        Node tem = new Node();
        int size;
        if (node == null) {
            return node;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.offer(node);

        while (!queue.isEmpty()) {
            size = queue.size();

            //node一开始是每层的第一个节点
            node = queue.peek();
            while (size > 0) {
                //目前的节点
                tem = queue.poll();
                if (node != tem) {//不处理每层的第一项
                    node.next = tem;
                }
                node = tem;

                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
        }
        return root;
    }

    public Node connect2(Node root) {
        if (root == null) {
            return null;
        }
        if (root.left != null) {
            root.left.next = root.right;
            if (root.next != null) {
                root.right.next = root.next.left;
            }
        }
        connect2(root.left);
        connect2(root.right);
        return root;
    }

    /**
     * 代码随想录的方法
     *
     * @param root
     * @return
     */
    public Node connect3(Node root) {
        Queue<Node> tmpQueue = new LinkedList<Node>();
        if (root != null) tmpQueue.add(root);

        while (tmpQueue.size() != 0) {
            int size = tmpQueue.size();

            Node cur = tmpQueue.poll();
            if (cur.left != null) tmpQueue.add(cur.left);
            if (cur.right != null) tmpQueue.add(cur.right);

            for (int index = 1; index < size; index++) {
                Node next = tmpQueue.poll();
                if (next.left != null) tmpQueue.add(next.left);
                if (next.right != null) tmpQueue.add(next.right);

                cur.next = next;
                cur = next;
            }
        }

        return root;
    }
}

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;
}
